package com.fduss.mazegame.client.gui.fxgui;

import com.fduss.mazegame.CLOptions;
import com.fduss.mazegame.client.Localizer;
import com.fduss.mazegame.core.Update;
import com.fduss.mazegame.core.unit.feature.Icon;
import com.fduss.mazegame.server.Server;
import com.fduss.mazegame.util.Queue;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;

import java.util.HashMap;
import java.util.Map;

/**
 * a java fx gui based on color
 *
 * @Author duocai wu
 * @Date 2017/9/27
 * @Time 23:31
 */
public class CorGui extends FxGui {

    private Map<Icon, Color> colorMap = new HashMap<>();

    private Rectangle[][] mapTiles;

    public CorGui() {
    }

    public static void main(String[] args) {
        opts = CLOptions.getInstance(args);
        // @TODO must use static server object at this time, address it later
        launch();
    }

    private Rectangle newRectangle(Icon icon) {
        Rectangle rect = new Rectangle(TILE_SIZE, TILE_SIZE);
        rect.setFill(iconToColor(icon));
        return rect;
    }

    private Color iconToColor(Icon icon) {
        Color c = colorMap.get(icon);
        if (c == null)
            throw new IllegalArgumentException(icon.toString());
        return c;
    }

    protected void initResources() {
        TILE_SIZE = 20;
        // init color sources
        colorMap.put(Icon.WALL, Color.BLACK);
        colorMap.put(Icon.EMPTY, Color.GRAY);
        colorMap.put(Icon.HERO, Color.BLUE);
        colorMap.put(Icon.END, Color.GREEN);
        colorMap.put(Icon.FOOTPRINT, Color.BURLYWOOD);
        colorMap.put(Icon.MONSTER, Color.MAGENTA);
    }

    protected void updateMap(Icon[][] icons) {
        int numRows = icons.length;
        int numCols = icons[0].length;
        mapTiles = new Rectangle[numRows][numCols];
        // north wall
        for (int c = 0; c < numCols + 2; c++) {
            map.add(newRectangle(Icon.WALL), c, 0);
        }
        for (int r = 0; r < numRows; r++) {
            // west wall
            map.add(newRectangle(Icon.WALL), 0, r + 1);
            // maze contents
            for (int c = 0; c < numCols; c++) {
                mapTiles[r][c] = newRectangle(icons[r][c]);
                map.add(mapTiles[r][c], c + 1, r + 1);
            }
            // east wall
            map.add(newRectangle(Icon.WALL), numCols + 1, r + 1);
        }
        // south wall
        for (int c = 0; c < numCols + 2; c++) {
            map.add(newRectangle(Icon.WALL), c, numRows + 1);
        }
    }

    protected void showUpdates(Queue<Update> updates) {
        while (!updates.isEmpty()) {
            Update update = updates.dequeue();
            int row = update.getRow();
            int col = update.getCol();
            Icon icon = update.getIcon();
            Rectangle rect = mapTiles[row][col];
            rect.setFill(iconToColor(icon));
        }
    }
}
